<template>
  <!-- 推荐上架 -->
  <div id="PrinterSettings">
    <root name="PrinterSettings">
      <SafeHeader
        v-bind="{
          title: '打印机设置',
          isBack: true,
          fixedTop: true,
        }"
      />
      <div class="printerSettings_wrap">
        <v-container>
          <v-card outlined class="py-2">
            <v-row class="ma-0">
              <v-col
                class="py-0 d-flex align-center font-weight-bold"
                style="font-size: 15px"
              >
                打印机MAC地址
              </v-col>
              <v-col cols="12" class="py-1">
                <v-text-field
                  readonly
                  v-model="uuid"
                  hint="连接蓝牙后会自动录入"
                ></v-text-field>
              </v-col>
            </v-row>
          </v-card>
        </v-container>
        <v-container class="px-0 printerSettings_content" style="flex: 1">
          <v-card outlined class="py-3 d-flex flex-column">
            <v-row class="ma-0" style="max-height: 32px">
              <v-col cols="9" class="py-1 printerSettings_content_title"
                >可连接设备列表</v-col
              >
              <v-col cols="3" class="py-1 printerSettings_content_title"
                ><v-btn depressed small rounded @click.stop="initBluetooth()"
                  >搜索</v-btn
                ></v-col
              >
            </v-row>
            <v-divider class="my-2 mx-3"></v-divider>
            <v-row class="ma-0 px-2 py-1">
              <v-col
                v-for="(item, index) in printItems"
                :key="index"
                cols="12"
                class="
                  pa-0
                  mb-3
                  printerSettings_content_content
                  d-flex
                  justify-space-between
                  align-center
                "
              >
                <v-icon class="printerSettings_content_content_icon">{{
                  printer
                }}</v-icon>
                <v-row class="ma-0" style="flex: 1">
                  <v-col
                    class="pa-0 d-flex align-center font-weight-bold"
                    style="font-size: 15px; color: #627aec"
                  >
                    {{ item.name }}
                  </v-col>
                  <v-col cols="12" class="pa-0">
                    <v-text-field
                      disabled
                      placeholder="正在搜索..."
                      dense
                      hide-details
                    ></v-text-field>
                  </v-col>
                </v-row>
                <v-btn
                  dark
                  rounded
                  small
                  color="#627AEC"
                  @click="connectBluetooth(item)"
                  >连接</v-btn
                >
              </v-col>
            </v-row>
          </v-card>
        </v-container>

        <v-bottom-navigation fixed>
          <v-row class="ma-0 pa-2">
            <v-col class="pa-0">
              <v-btn
                block
                color="#193690"
                dark
                style="height: 100%; border-radius: 8px"
                @click="doSave"
                :loading="loading"
                ><span
                  style="color: #fff; font-size: 15px"
                  class="font-weight-bold"
                  >保存并测试</span
                ></v-btn
              >
            </v-col>
          </v-row>
        </v-bottom-navigation>
      </div>
    </root>
    <v-overlay :value="overlay">
      <v-progress-circular indeterminate size="64"></v-progress-circular>
    </v-overlay>
  </div>
</template>

<script>
import Root from "@/components/Root.vue";
import SafeHeader from "../../components/safeHeader_wms";
import { mdiPrinterWireless } from "@mdi/js";
import { printToJiaBo } from "@/static/print";

export default {
  name: "ShelfRecommended",
  components: {
    SafeHeader,
    Root,
  },
  data() {
    return {
      overlay: false,
      loading: false,
      uuid: "", // 打印机uuid
      printer: mdiPrinterWireless,
      printItems: [],
      clearly: null,
    };
  },
  methods: {
    // 初始化蓝牙模块
    initBluetooth() {
      // setTimeout(() => {
      let bluetooth = window.api.require("ble");
      bluetooth.initManager((ret) => {
        if (ret.state == "poweredOn") {
          bluetooth.scan({ serviceUUIDs: [] }, (ret, err) => {
            if (ret.status) {
              this.clearly = setInterval(() => {
                bluetooth.getPeripheral((ret) => {
                  if (ret.peripherals.length != 0) {
                    let bths = [];
                    ret.peripherals.forEach((ph) => {
                      if (ph.name && ph.uuid) {
                        bths.push(ph);
                      }
                    });
                    // console.log("可用蓝牙===>" + JSON.stringify(bths));
                    this.printItems = bths;
                  }
                });
              }, 3000);
            }
          });
        } else {
          this.$confirm("请开启蓝牙!");
        }
      });
      // }, 1000)
    },

    // 连接蓝牙
    connectBluetooth(item) {
      let this_ = this;
      clearInterval(this.clearly);

      this.uuid = item.uuid;
      let ble = window.api.require("ble");

      ble.connect(
        {
          peripheralUUID: this.uuid,
        },
        function (ret, err) {
          if (ret.status) {
            this_.uuid = this_.replacepos(item.uuid, 4, 4, "1");
            alert("连接成功！");
          } else {
            console.log(err.code);
          }
        }
      );
    },
    // 保存并测试
    doSave() {
      let that = this;
      if (that.uuid) {
        that.loading = true;
        localStorage.setItem("uuid", that.uuid);
        console.log(localStorage.getItem("uuid"));

        let printModule = window.api.require("moduleDemo");
        let params = {
          mac: localStorage.getItem("uuid"),
        };
        printModule.printConnect(params, function (ret) {
          that.loading = false;
          window.api.toast({ msg: ret.result, location: "middle" });
          // alert(ret.result);

          printToJiaBo(
            "ABC-DEF-110",
            "测试-物料名称",
            "20220101001",
            100,
            "BOX-111"
          );
        });
        this.loading = false;
      } else {
        alert("请先连接蓝牙打印机");
      }
    },
    // 校验
    // macFormCheck(macCode) {
    //   let macs = [];
    //   macs = macCode.split(":");
    //   if (macs.length != 6) {
    //     window.api.alert({
    //       title: "提示",
    //       msg: "输入的mac地址格式不正确，请以xx:xx:xx:xx:xx:xx的形式输入（xx为16进制数字）!",
    //     });
    //     return false;
    //   }
    //   for (let s = 0; s < 6; s++) {
    //     let temp = parseInt(macs[s], 16);

    //     if (isNaN(temp)) {
    //       window.api.alert({
    //         title: "提示",
    //         msg: "输入的mac地址格式不正确，请以xx:xx:xx:xx:xx:xx的形式输入（xx为16进制数字）!",
    //       });
    //       return false;
    //     }
    //     if (temp < 0 || temp > 255) {
    //       window.api.alert({
    //         title: "提示",
    //         msg: "输入的mac地址格式不正确，请以xx:xx:xx:xx:xx:xx的形式输入（xx为16进制数字）!",
    //       });
    //       return false;
    //     }
    //   }
    //   return true;
    // },

    //工具方法：替换第一个1
    replacepos(text, start, stop, replacetext) {
      let mystr =
        text.substring(0, start - 1) + replacetext + text.substring(stop);
      return mystr;
    },
  },
  mounted() {
    this.initBluetooth();
    this.uuid = localStorage.getItem("uuid");
  },
};
</script>

<style lang="scss" scoped>
.scanContainer > .row {
  margin: 0;
  padding: 10px;
}

.inputPlaceholder {
  ::v-deep.v-text-field__slot {
    input::-webkit-input-placeholder,
    input::-moz-placeholder,
    input:-moz-placeholder,
    input:-ms-input-placeholder {
      font-size: 15px;
    }
  }
}
.printerSettings_wrap {
  .printerSettings_content_content {
    .printerSettings_content_content_icon {
      display: block;
      width: 55px;
      height: 55px;
      display: flex;
      justify-content: center;
      align-items: center;
      padding: 5px;
      ::v-deep.v-icon__svg {
        width: 30px;
        height: 30px;
      }
    }
  }
  .printerSettings_content {
    padding-bottom: 60px;
  }
}
</style>
